package www.cslc.com.Util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class ConfigFileTools {
	private Properties properties;
	private String configFile;
	@SuppressWarnings("rawtypes")
	private Map propertiesMap = new HashMap();
	public ConfigFileTools(String confile) {
		this.configFile = confile;
		init();
	}
	@SuppressWarnings("unchecked")
	public void init() {
		properties = new Properties();
		InputStream is = null;
		try {
			is = new FileInputStream(configFile);
			properties.load(is);
			propertiesMap.putAll(properties);
		} catch (Exception ex) {
			System.out.println("Can't read the properties file. " + ex);
		} finally {
			try {
				if (is != null)
					is.close();
			} catch (IOException exception) {
				// ignored
			}
		}
	}
	/**
	 * Retun a value for certain key.
	 * 
	 * @param key a certain key define in properties file.
	 * @return value
	 */
	public String getValue(String key) {
		return properties.getProperty(key);
	}

	/**
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public String getValue(String key, String defaultValue) {
		String value = properties.getProperty(key);
		if (value == null)
			value = defaultValue;
		return value;
	}

	/**
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public boolean getValue(String key, boolean defaultValue) {
		String str = getValue(key, "false");
		boolean value = str.equalsIgnoreCase("true");
		return value;
	}


	/**
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public Map getPropertiesMap() {
		return propertiesMap;
	}

	public void updateProperties(String key, String value) {
		properties.put(key, value);
	}

	public boolean updatePropertiesFile() {
		try {
			properties.store(new FileOutputStream(configFile), null);
		} catch (FileNotFoundException e) {
			System.out.println("PropertiesFile not found");
			return false;
		} catch (IOException e) {
			System.out.println("PropertiesFile write fail");
			return false;
		}
		return true;
	}

}
